/**
 * 
 */
package org.o14x.alpha.ui.commands.rename;

import java.io.File;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.PlatformUI;
import org.o14x.alpha.ui.controller.UIController;
import org.o14x.alpha.ui.views.folder.FolderView;
import org.o14x.alpha.ui.views.foldertree.FolderTreeInput;
import org.o14x.alpha.ui.views.foldertree.FolderTreeView;

/**
 * Delete command.
 * 
 * @author Olivier DANGREAUX
 */
public class RenameCommand extends AbstractHandler {
	private UIController uiController;

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IStructuredSelection selection = null;

		if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getFolderView().getTableViewer().getSelection();
		} else if (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart() instanceof FolderTreeView) {
			selection = (IStructuredSelection) uiController.getDomain().getCurrentExplorerTab().getExplorerTreeViewer().getSelection();
		}

		if (selection != null && !selection.isEmpty()) {
			if (selection.size() == 1) {
				File file = (File) selection.getFirstElement();

				RenameInputDialog renameInputDialog = new RenameInputDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), file.getName(), new RenameInputValidator(file.getName()));
				renameInputDialog.setUiController(uiController);
				renameInputDialog.open();
				String newName = renameInputDialog.getValue();
				if (newName != null && !newName.equals(file.getName())) {
					File newFile = new File(file.getParentFile(), newName);
					file.renameTo(newFile);

					uiController.getDomain().getCurrentExplorerTab().getFolderView().update();
					TreeViewer treeViewer = uiController.getDomain().getCurrentExplorerTab().getExplorerTreeViewer();
					FolderTreeInput folderTreeInput = (FolderTreeInput) treeViewer.getInput();
					folderTreeInput.refresh();
					treeViewer.refresh();
				}
			}
		}

		return null;

	}

	/**
	 * Returns the value of uiController.
	 *
	 * @return The value of uiController.
	 */
	public UIController getUiController() {
		return uiController;
	}

	/**
	 * Sets the value of uiController.
	 *
	 * @param uiController The value of uiController to set.
	 */
	public void setUiController(UIController uiController) {
		this.uiController = uiController;
	}
}
